﻿using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using XfTechOAWeb.Dtos.MyMessages;
using XfTechOAWeb.IService;
using XfTechOAWeb.Models;
using XfTechOAWeb.Service;

namespace XfTechOAWeb.Service.Hubs
{
    /// <summary>
    /// Hub中心
    /// </summary>
    public class MessageHub : Hub<IChatClient>
    {
        readonly IMyMessageService _myMessage;

        //用户和connectionId之间的字典
        private static ConcurrentDictionary<string, string> _connectionIds = new ConcurrentDictionary<string, string>();

        public MessageHub(IMyMessageService myMessage)
        {
            _myMessage = myMessage;
        }

        /// <summary>
        /// 向所有已连接的客户端发送消息
        /// Clients.All
        /// </summary>
        /// <param name="user"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.ReceiveMessage(user, message);
        }

        /// <summary>
        /// 客户端连接服务端
        /// </summary>
        /// <returns></returns>
        public async override Task OnConnectedAsync()
        {
            //Console.WriteLine($"建立连接{Context.ConnectionId}");
            _connectionIds[Context.ConnectionId] = Context.GetHttpContext().Request.Query["userName"].ToString();
            
            // 添加到一个组下
            //await Groups.AddToGroupAsync(Context.ConnectionId, "SignalR Users");
            //发送上线消息
            //await Clients.All.SendAsync("ReceiveMessage", 1, new { title = "系统消息", content = $"{Context.ConnectionId} 上线" });

            await base.OnConnectedAsync();
        }
        /// <summary>
        /// 客户端断开连接
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public async override Task OnDisconnectedAsync(Exception exception)
        {
            var cid = Context.ConnectionId;//也可以从缓存中获取ConnectionId

            //Console.WriteLine($"断开连接{Context.ConnectionId}");
            //从组中删除
            // await Groups.RemoveFromGroupAsync(Context.ConnectionId, "SignalR Users");

            //移除缓存
            if (_connectionIds.TryRemove(cid, out string value))
            {

            }
            //  await Clients.Client(cid).SendAsync("ReceiveMessage", 3, new { title = "系统消息", content = "离线成功" });

            await base.OnDisconnectedAsync(exception);
        }


        /// <summary>
        /// 根据用户名获取所有的客户端
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public static IEnumerable<string> GetCnnectionIds(string username)
        {
            foreach (var item in _connectionIds)
            {
                if (item.Value == username)
                {
                    yield return item.Key;
                }
            }
        }
    }
}
